const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const mongoose = require('mongoose');
const logger = require('morgan');
const { connectDB } = require('./config/database');
const uploadRouter = require('./routes/upload');
const cors = require('cors');
const sharesRouter = require('./routes/shares');
const pddRouter = require('./routes/pdd');
const dictRouter = require('./routes/dict');
const authRouter = require('./routes/auth');  // 认证路由
const userRouter = require('./routes/users');  // 用户管理路由
const adminRoutes = require('./routes/admin');
const h5Routes = require('./routes/h5');

// JWT密钥
const JWT_SECRET = 'long';

// 白名单路由
const apiWhiteList = [
	'/admin/auth/login',  // 管理后台登录
	'/auth/login',        // PC端登录
	'/upload/single',     // 文件上传
];

const h5WhiteList = [
	'/auth/login',     // H5登录
	'/auth/register',  // H5注册
	'/dict/list',     // H5字典列表
	'/products/list', // H5产品列表
	'/categories/list', // H5分类列表
	'/brands/list',   // H5品牌列表
];

// API认证中间件
const apiAuthMiddleware = (req, res, next) => {
	// 如果是H5的路由，直接跳过
	if (req.path.startsWith('/h5Api')) {
		return next();
	}

	// 如果是白名单路由，直接通过
	if (apiWhiteList.includes(req.path)) {
		return next();
	}

	const token = req.headers.authorization?.split(' ')[1];
	
	if (!token) {
		return res.status(401).json({
			code:500,
			message: '未登录或登录已过期1'
		});
	}

	try {
		const decoded = jwt.verify(token, JWT_SECRET);
		req.user = decoded;
		next();
	} catch (error) {
		return res.status(401).json({
			code:500,
			message: '未登录或登录已过期2'
		});
	}
};

// H5认证中间件
const h5AuthMiddleware = (req, res, next) => {
	// 调试日志
	console.log('H5 Auth Check:', {
		originalPath: req.originalUrl,
		path: req.path,
		baseUrl: req.baseUrl,
		whiteList: h5WhiteList
	});

	// 如果是白名单路由，直接通过
	if (h5WhiteList.includes(req.path)) {
		console.log('Path is in whitelist');
		return next();
	}
	console.log('Path is NOT in whitelist');

	const token = req.headers.authorization?.split(' ')[1];
	
	if (!token) {
		return res.status(401).json({
			code:500,
			message: '未登录或登录已过期3'
		});
	}

	try {
		const decoded = jwt.verify(token, JWT_SECRET);
		req.user = decoded;
		next();
	} catch (error) {
		return res.status(401).json({
			code:500,
			message: '未登录或登录已过期4'
		});
	}
};

// 导入路由
const routes = {
	index: require('./routes/index'),
	auth: require('./routes/users'),         // 重命名users为auth，因为这里主要处理认证相关
	resumes: require('./routes/resumes'),
	collections: require('./routes/collections'),
	resumeTemplates: require('./routes/resumeTemplates'),
	images: require('./routes/imgs'),        // 统一命名
	clubs: require('./routes/clubs'),
	articles: require('./routes/articles'),
	apps: require('./routes/appLists'),      // 简化命名
	banners: require('./routes/banners'),
	sidebar: require('./routes/sidebarAdImgs'),
	links: require('./routes/links'),
	comments: require('./routes/comments'),
	plans: require('./routes/planLists'),    // 简化命名
	blogs: require('./routes/blogs'),
	insurances: require('./routes/insurances'),
	menus: require('./routes/menus'),
	categories: require('./routes/categories'),
	brands: require('./routes/brands'),
	products: require('./routes/products'),
	shares: require('./routes/shares')
};

const app = express();

// 视图引擎设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 应用基本中间件
app.use(logger('dev'));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 允许跨域
app.use(cors({
	origin: '*',
	credentials: false,
	methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
	allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
}));

// 添加调试日志中间件
app.use((req, res, next) => {
	console.log('Received request:', req.method, req.url);
	next();
});

// 添加静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));

// 创建一个 API 路由器
const apiRouter = express.Router();

// 将 H5 路由挂载到 /h5Api 路径，并应用H5认证中间件
app.use('/h5Api', h5AuthMiddleware, h5Routes);

// 直接挂载不需要认证的路由到app上
app.use('/api/auth', authRouter);  // 认证相关路由
app.use('/api/upload', uploadRouter);  // 文件上传路由

// 应用认证中间件到API路由器
apiRouter.use(apiAuthMiddleware);

// 注册需要认证的 API 路由
apiRouter.use('/admin', adminRoutes);  // 管理后台路由
apiRouter.use('/users', userRouter);  // 用户管理路由（使用复数形式）
apiRouter.use('/resumes', routes.resumes);
apiRouter.use('/resume-templates', routes.resumeTemplates);
apiRouter.use('/collections', routes.collections);
apiRouter.use('/images', routes.images);
apiRouter.use('/clubs', routes.clubs);
apiRouter.use('/articles', routes.articles);
apiRouter.use('/apps', routes.apps);
apiRouter.use('/banners', routes.banners);
apiRouter.use('/sidebar', routes.sidebar);
apiRouter.use('/links', routes.links);
apiRouter.use('/comments', routes.comments);
apiRouter.use('/plans', routes.plans);
apiRouter.use('/blogs', routes.blogs);
apiRouter.use('/insurances', routes.insurances);
apiRouter.use('/menus', routes.menus);
apiRouter.use('/categories', routes.categories);
apiRouter.use('/brands', routes.brands);
apiRouter.use('/products', routes.products);
apiRouter.use('/shares', sharesRouter);
apiRouter.use('/pdd', pddRouter);
apiRouter.use('/dict', dictRouter);

// 将 API 路由器挂载到 /api 路径
app.use('/api', apiRouter);

// 4. 注册非 API 路由
app.use('/', routes.index);

// 404错误处理
app.use('*', (req, res) => {
	console.log('404 Not Found:', {
		path: req.path,
		originalUrl: req.originalUrl,
		method: req.method,
		body: req.body
	});

	res.header("Content-Type", "text/html");
	res.status(404).render('error', {
		code: 404,
		message: '接口地址不存在',
		error: {
			path: `${req.headers.host}${req.baseUrl}`,
			method: req.method,
			timestamp: new Date().toLocaleString('zh-CN'),
			suggestions: [
				'请检查接口地址是否正确',
				'请检查请求方式(GET/POST/PUT/DELETE)是否正确',
				'请确认接口是否已部署'
			]
		}
	});
});

// 全局错误处理
app.use((err, req, res, next) => {
	const isApiRequest = ['/api', '/auth', '/resumes', '/articles', '/comments', '/clubs']
		.some(path => req.path.includes(path));

	if (isApiRequest) {
		return next(err);
	}

	res.status(err.status || 500).render('error', {
		code: err.status || 500,
		message: err.message || '服务器内部错误',
		error: {
			path: `${req.headers.host}${req.baseUrl}`,
			method: req.method,
			timestamp: new Date().toLocaleString('zh-CN'),
			suggestions: [
				'请稍后重试',
				'如果问题持续存在，请联系管理员'
			]
		}
	});
});

// 连接数据库
connectDB().then(() => {
	console.log('数据库连接已就绪');
	// 启动服务器
	const PORT = process.env.PORT || 3003;
	app.listen(PORT, () => {
		console.log(`服务器运行在端口 ${PORT}`);
	});
});

module.exports = app;
